
#include <ctype.h>
#include <errno.h>
#include <libgen.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include <net/if.h>
#include <sys/epoll.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <filesystem>  

#include <linux/can.h>
#include <linux/can/raw.h>
#include <linux/net_tstamp.h>

#include <fstream>  
#include <iostream> 

#include "lib.h"

namespace fs = std::filesystem;  

#ifndef SO_TIMESTAMPING
#define SO_TIMESTAMPING 37
#endif

#define MAX_DEVICES 4 /* max. number of devices interfaces */
#define MAX_NAME_LEN 16 /* string 'absolute with names' requires max 16 bytes */
#define TIMESTAMPSZ 50 /* string 'absolute with date' requires max 49 bytes */

#define MAXSOCK 16 /* max. number of CAN interfaces given on the cmdline */
#define MAXIFNAMES 30 /* size of receive name index to omit ioctls */
#define MAXCOL 6 /* number of different colors for colorized output */
#define ANYDEV "any" /* name of interface to receive from any CAN interface */
#define ANL "\r\n" /* newline in ASC mode */

#define BOLD ATTBOLD
#define RED (ATTBOLD FGRED)
#define GREEN (ATTBOLD FGGREEN)
#define YELLOW (ATTBOLD FGYELLOW)
#define BLUE (ATTBOLD FGBLUE)
#define MAGENTA (ATTBOLD FGMAGENTA)
#define CYAN (ATTBOLD FGCYAN)

// const size_t MAX_FILE_SIZE = 50 * 1024; 
struct if_info { /* bundled information per open socket */
	int s; /* socket */
	char *cmdlinename;
	__u32 dropcnt;
	__u32 last_dropcnt;
};
static struct if_info sock_info[MAXSOCK];

static char devname[MAXIFNAMES][IFNAMSIZ + 1];
static int dindex[MAXIFNAMES];
static int max_devname_len; /* to prevent frazzled device name output */
static const int canfd_on = 1;
static volatile int running = 1;

static int idx2dindex(int ifidx, int socket)
{
	int i;
	struct ifreq ifr;

	for (i = 0; i < MAXIFNAMES; i++) {
		if (dindex[i] == ifidx)
			return i;
	}

	/* create new interface index cache entry */
	/* remove index cache zombies first */
	for (i = 0; i < MAXIFNAMES; i++) {
		if (dindex[i]) {
			ifr.ifr_ifindex = dindex[i];
			if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
				dindex[i] = 0;
		}
	}

	for (i = 0; i < MAXIFNAMES; i++)
		if (!dindex[i]) /* free entry */
			break;

	if (i == MAXIFNAMES) {
		fprintf(stderr, "Interface index cache only supports %d interfaces.\n",
			MAXIFNAMES);
		exit(1);
	}

	dindex[i] = ifidx;

	ifr.ifr_ifindex = ifidx;
	if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
		perror("SIOCGIFNAME");

	if (max_devname_len < (int)strlen(ifr.ifr_name))
		max_devname_len = strlen(ifr.ifr_name);

	strcpy(devname[i], ifr.ifr_name);

	pr_debug("new index %d (%s)\n", i, devname[i]);

	return i;
}

static inline void sprint_timestamp(const struct timeval *tv, struct timeval *const last_tv, char *ts_buffer)
{
	struct tm tm;
	char timestring[25];

	tm = *localtime(&tv->tv_sec);
	strftime(timestring, 24, "%Y-%m-%d %H:%M:%S", &tm);
	sprintf(ts_buffer, "[%s.%06llu] ", timestring, (unsigned long long)tv->tv_usec);
}


void stop() 
{
	running = 0;
}

int canlog(const char *names, size_t size)
{
	int fd_epoll;
	struct epoll_event events_pending[MAXSOCK];
	struct epoll_event event_setup = {
		.events = EPOLLIN, /* prepare the common part */
	};

	unsigned char down_causes_exit = 1;
	int count = 0;
	int rcvbuf_size = 0;
	int opt, num_events;
	int currmax = MAX_DEVICES, numfilter;
	int join_filter;
	char *ptr, *nptr;
	struct sockaddr_can addr = {
		.can_family = AF_CAN,
	};
	char ctrlmsg[CMSG_SPACE(sizeof(struct timeval)) +
		     CMSG_SPACE(3 * sizeof(struct timespec)) +
		     CMSG_SPACE(sizeof(__u32))];

	struct iovec iov;
	struct msghdr msg;
	struct cmsghdr *cmsg;
	struct can_filter *rfilter;
	can_err_mask_t err_mask;
	struct canfd_frame frame;
	int nbytes, i, maxdlen;
	struct ifreq ifr;
	struct timeval tv, last_tv;
	int timeout_ms = -1; /* default to no timeout */
	std::string fname, fname_1, fname_2; 
    char dev[MAX_DEVICES][MAX_NAME_LEN] = {{0}};

    std::fstream logfile; 

	last_tv.tv_sec = 0;
	last_tv.tv_usec = 0;

    if (!names || *names == '\0') {
        fprintf(stderr, "device names are null\n");
        return -1;
    }

    char *input_copy = strdup(names);
    if (!input_copy) {
        fprintf(stderr, "can not malloc names\n");
        return -2;
    }

    int dev_count = 0;

    char *token = strtok(input_copy, ",");
    while (token != NULL && dev_count < MAX_DEVICES) 
    {
        char *start = token;
        while (isspace((unsigned char)*start)) start++;
        
        char *end = start + strlen(start) - 1;
        while (end > start && isspace((unsigned char)*end)) end--;
        *(end + 1) = '\0';

        if (*start != '\0') 
        {
            if (strlen(start) >= MAX_NAME_LEN) {
                fprintf(stderr, "names to long '%s'\n", start);
                return -3;
            }

            strncpy(dev[dev_count], start, MAX_NAME_LEN);
            printf("get device name: %s\n", dev[dev_count]);
            dev_count++;
        }

        token = strtok(NULL, ",");
    }

    if (token != NULL) {
        fprintf(stderr, "devices over load (%d)\n", MAX_DEVICES);
        return -3;
    }

    currmax = dev_count;
    
	fd_epoll = epoll_create(1);
	if (fd_epoll < 0) {
		perror("epoll_create");
		return 1;
	}

	for (i = 0; i < currmax; i++) {
		struct if_info *obj = &sock_info[i];
		ptr = dev[i];
		nptr = strchr(ptr, ',');

		pr_debug("open %d '%s'.\n", i, ptr);

		obj->s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
		if (obj->s < 0) {
			perror("socket");
			return 1;
		}

		event_setup.data.ptr = obj; /* remember the instance as private data */
		if (epoll_ctl(fd_epoll, EPOLL_CTL_ADD, obj->s, &event_setup)) {
			perror("failed to add socket to epoll");
			return 1;
		}

		obj->cmdlinename = ptr; /* save pointer to cmdline name of this socket */

		if (nptr)
			nbytes = nptr - ptr; /* interface name is up the first ',' */
		else
			nbytes = strlen(ptr); /* no ',' found => no filter definitions */

		if (nbytes >= IFNAMSIZ) {
			fprintf(stderr, "name of CAN device '%s' is too long!\n", ptr);
			return 1;
		}

		if (nbytes > max_devname_len)
			max_devname_len = nbytes; /* for nice printing */

		memset(&ifr.ifr_name, 0, sizeof(ifr.ifr_name));
		strncpy(ifr.ifr_name, ptr, nbytes);

		pr_debug("using interface name '%s'.\n", ifr.ifr_name);

		if (strcmp(ANYDEV, ifr.ifr_name) != 0) {
			if (ioctl(obj->s, SIOCGIFINDEX, &ifr) < 0) {
				perror("SIOCGIFINDEX");
				exit(1);
			}
			addr.can_ifindex = ifr.ifr_ifindex;
		} else
			addr.can_ifindex = 0; /* any can interface */

		/* try to switch the socket into CAN FD mode */
		setsockopt(obj->s, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on));

		if (rcvbuf_size) {
			int curr_rcvbuf_size;
			socklen_t curr_rcvbuf_size_len = sizeof(curr_rcvbuf_size);

			/* try SO_RCVBUFFORCE first, if we run with CAP_NET_ADMIN */
			if (setsockopt(obj->s, SOL_SOCKET, SO_RCVBUFFORCE,
				       &rcvbuf_size, sizeof(rcvbuf_size)) < 0) {
				pr_debug("SO_RCVBUFFORCE failed so try SO_RCVBUF ...\n");
				if (setsockopt(obj->s, SOL_SOCKET, SO_RCVBUF,
					       &rcvbuf_size, sizeof(rcvbuf_size)) < 0) {
					perror("setsockopt SO_RCVBUF");
					return 1;
				}

				if (getsockopt(obj->s, SOL_SOCKET, SO_RCVBUF,
					       &curr_rcvbuf_size, &curr_rcvbuf_size_len) < 0) {
					perror("getsockopt SO_RCVBUF");
					return 1;
				}

				/* Only print a warning the first time we detect the adjustment */
				/* n.b.: The wanted size is doubled in Linux in net/sore/sock.c */
				if (!i && curr_rcvbuf_size < rcvbuf_size * 2)
					fprintf(stderr, "The socket receive buffer size was "
						"adjusted due to /proc/sys/net/core/rmem_max.\n");
			}
		}

		const int timestamp_on = 1;

		if (setsockopt(obj->s, SOL_SOCKET, SO_TIMESTAMP,
			       &timestamp_on, sizeof(timestamp_on)) < 0) {
			perror("setsockopt SO_TIMESTAMP");
			return 1;
		}	

		if (bind(obj->s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
			perror("bind");
			return 1;
		}
	}

	fname = std::string(getenv("HOME")) + "/log/can.log";
	fname_1 = std::string(getenv("HOME")) + "/log/can.1.log";
	fname_2 = std::string(getenv("HOME")) + "/log/can.2.log";

    logfile.open(fname, std::fstream::out | std::fstream::app);  
  
    if (!logfile.is_open()) {  
        perror("file open error！");  
        return 1;  
    }  
	
	/* these settings are static and can be held out of the hot path */
	iov.iov_base = &frame;
	msg.msg_name = &addr;
	msg.msg_iov = &iov;
	msg.msg_iovlen = 1;
	msg.msg_control = &ctrlmsg;

	while (running) {
		num_events = epoll_wait(fd_epoll, events_pending, currmax, timeout_ms);
		if (num_events == -1) {
			if (errno != EINTR)
				running = 0;
			continue;
		}

		/* handle timeout */
		if (!num_events && timeout_ms >= 0) {
			running = 0;
			continue;
		}

		for (i = 0; i < num_events; i++) { /* check waiting CAN RAW sockets */
			struct if_info *obj = (struct if_info*)events_pending[i].data.ptr;
			int idx;
			char *extra_info = "";

			/* these settings may be modified by recvmsg() */
			iov.iov_len = sizeof(frame);
			msg.msg_namelen = sizeof(addr);
			msg.msg_controllen = sizeof(ctrlmsg);
			msg.msg_flags = 0;

			nbytes = recvmsg(obj->s, &msg, 0);
			idx = idx2dindex(addr.can_ifindex, obj->s);

			if (nbytes < 0) {
				if ((errno == ENETDOWN) && !down_causes_exit) {
					fprintf(stderr, "%s: interface down\n", devname[idx]);
					continue;
				}
				perror("read");
				return 1;
			}

			if ((size_t)nbytes == CAN_MTU)
				maxdlen = CAN_MAX_DLEN;
			else if ((size_t)nbytes == CANFD_MTU)
				maxdlen = CANFD_MAX_DLEN;
			else {
				fprintf(stderr, "read: incomplete CAN frame\n");
				return 1;
			}

			if (count && (--count == 0))
				running = 0;

			for (cmsg = CMSG_FIRSTHDR(&msg);
			     cmsg && (cmsg->cmsg_level == SOL_SOCKET);
			     cmsg = CMSG_NXTHDR(&msg,cmsg)) {
				if (cmsg->cmsg_type == SO_TIMESTAMP) {
					memcpy(&tv, CMSG_DATA(cmsg), sizeof(tv));
				} else if (cmsg->cmsg_type == SO_TIMESTAMPING) {
					struct timespec *stamp = (struct timespec *)CMSG_DATA(cmsg);

					/*
					 * stamp[0] is the software timestamp
					 * stamp[1] is deprecated
					 * stamp[2] is the raw hardware timestamp
					 * See chapter 2.1.2 Receive timestamps in
					 * linux/Documentation/networking/timestamping.txt
					 */
					tv.tv_sec = stamp[2].tv_sec;
					tv.tv_usec = stamp[2].tv_nsec / 1000;
				} else if (cmsg->cmsg_type == SO_RXQ_OVFL) {
					memcpy(&obj->dropcnt, CMSG_DATA(cmsg), sizeof(__u32));
				}
			}

			/* check for (unlikely) dropped frames on this specific socket */
			if (obj->dropcnt != obj->last_dropcnt) {
				__u32 frames = obj->dropcnt - obj->last_dropcnt;

                std::string temp = (frames > 1)?"s":"";
				logfile << "DROPCOUNT: dropped " << frames << " CAN frame" << temp << " on " << devname[idx] << " socket (total drops" << obj->dropcnt <<")" << std::endl;

				obj->last_dropcnt = obj->dropcnt;
			}

			
			if (msg.msg_flags & MSG_DONTROUTE)
				extra_info = " T";
			else
				extra_info = " R";
		
			char buf[CL_CFSZ]; /* max length */
			char ts_buf[TIMESTAMPSZ];

			sprint_timestamp(&tv, &last_tv, ts_buf);

			/* log CAN frame with absolute timestamp & device */
			sprint_canframe(buf, &frame, 0, maxdlen);
			logfile << ts_buf << " " << devname[idx] << " " << buf << extra_info << std::endl;
		}

		logfile.seekg(0, std::ios::end);  
		
	    if (logfile.tellg() > size) {   
	    
	        pr_debug("File size exceeds the limit. backup file content.\n");
	        logfile.close();

	        if (fs::exists(fname_1)) {  
		        if (fs::exists(fname_2)) {
		        	if (!fs::remove(fname_2)) {  
			            perror("Failed to delete file!");  
			            return 1;  
			        }  
		        }
		        
		        fs::rename(fname_1, fname_2);
		    }  
	        
	        fs::rename(fname, fname_1);

	        logfile.open(fname, std::fstream::out | std::fstream::app);
	        if (!logfile.is_open()) {
	            perror("Error reopening file.");
	            return 1;
	        }
	    }
	}

	for (i = 0; i < currmax; i++)
		close(sock_info[i].s);

	close(fd_epoll);

	logfile.close();

	return 0;
}
